//
//  LocationManager.m
//  Customer
//
//  Created by jiangxiaobai on 2017/9/12.
//  Copyright © 2017年 tangang. All rights reserved.
//

#import "LocationManager.h"
#import "UserModel.h"
#import <CoreLocation/CoreLocation.h>

@interface LocationManager()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager* locationManager;

@end

@implementation LocationManager{
    BOOL        isOK;
}

- (instancetype)init{
    if (self=[super init]) {
        
    }
    return self;
}

- (void)getUserLocation:(GetLocationBlock)success{
    _returnBlock=success;
    [self getGPS];
}


#pragma mark 定位信息开始
- (void)getGPS {
    isOK=NO;
    if (!self.locationManager) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate=self;
        if (! [CLLocationManager locationServicesEnabled]) {
            
        }
        else if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization];
            [self.locationManager startUpdatingLocation];
        }
        else {
            [self.locationManager requestAlwaysAuthorization];
            [self.locationManager startUpdatingLocation];
        }
    }else{
        [self.locationManager startUpdatingLocation];
    }
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    if (isOK) {
        return;
    }
    isOK=YES;
    CLLocation *newLocation = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    // 反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (! error) {
            if ([placemarks count] > 0) {
                CLPlacemark *placemark = [placemarks firstObject];
                
                // 获取城市
                NSString *city = placemark.locality;
                if (! city) {
                    // 6
                    city = placemark.administrativeArea;
                }
                _returnBlock(city);
                
            } else if ([placemarks count] == 0) {
                
            }
        }
    }];
    [self.locationManager stopUpdatingLocation];
}



static LocationManager *locationManager=nil;
+ (LocationManager *)manager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        locationManager =[[LocationManager alloc]init];
    });
    return locationManager;
}

@end
